package com.example.demo.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

public class CompressImg {
    public File getCompressPath(MultipartFile file) throws Exception {
        //未压缩前的上传路径
        File tofile=FolderUtils.multipartFileToFile(file);
        String fileSavePath = this.getClass().getResource("/").getPath()+"static/image/beforeCompress.jpg";
        File tempFile = new File(fileSavePath);
       // file.transferTo(tempFile);
        //压缩后的路径
        String smallFileSavePath = this.getClass().getResource("/").getPath()+"static/image/compress.jpg";
        //获取文件大小 KB
        long size = file.getSize()/1024;
        //判断文件大小对图片质量进行压缩,尺寸不变，范围0.01~1.0,值越低压缩效率越高。图片低于600K不进行压缩
        if(size>=7380){
            Thumbnails.of(tofile).scale(1f).outputQuality(0.01f).toFile(smallFileSavePath);
           // Thumbnails.of(fileSavePath).scale(1f).outputQuality(0.01f).toFile(smallFileSavePath);
            tempFile.delete();
        }else if(size>=4096&&size<7380){
            Thumbnails.of(tofile).scale(1f).outputQuality(0.2f).toFile(smallFileSavePath);
            tempFile.delete();
        }else if(size>=1024&&size<4096){
            Thumbnails.of(tofile).scale(1f).outputQuality(0.3f).toFile(smallFileSavePath);
            tempFile.delete();
        }else if(size>=600&&size<1024){
            Thumbnails.of(tofile).scale(1f).outputQuality(1f).toFile(smallFileSavePath);
            tempFile.delete();
        }else{
            return tofile;
        }
        File compressFile=new File(smallFileSavePath);
        return compressFile;
    }
}
